#!/usr/bin/env bash

CMD=${1:-start}
PORT=${2:-12698}
SSH_PORT=${3:-12699}
MEMORY_LIMIT="$(($(free -g | grep -oP "Mem:\s+\K\d+")-1))g"
MEMORY_SWAP_LIMIT="-1"
USER=$(id -nu)
MACHINE_NAME="$(hostname)"
IMAGE=docker.peidan.me/${USER}/xz-basic-cpu
NAME=${USER}-basic-cpu

echo MEMORY_LIMIT=${MEMORY_LIMIT}
echo MEMORY_SWAP_LIMIT=${MEMORY_SWAP_LIMIT}
echo IMAGE=${IMAGE}
echo CPU_LIMIT=${CPU_LIMIT}
echo CMD=${CMD}
if [ ${CMD} == "build" ]; then
    sudo docker build . -t ${IMAGE} --build-arg USER=${USER} --build-arg USER_ID="$(id -u)" --build-arg SSH_PORT=${SSH_PORT};
    sudo docker push ${IMAGE}:latest;
elif [ ${CMD} == "start" ]; then
    sudo docker run -d --name ${NAME} --restart=unless-stopped --shm-size="4g" \
    --user root \
    --net=host \
    --memory ${MEMORY_LIMIT} \
    -v "$(realpath ~/docker-env/)":/shared_data \
    -v /tmp:/tmp \
    -v /srv/data:/srv/data \
    -v /mnt/mfs:/mnt/mfs \
    -v "$(realpath ~/Project/)":/root/Project \
    ${IMAGE} \
    sleep infinity;
    echo "Starting your docker..."
    sleep 5s;
    sudo docker exec -it -u root ${NAME} bash -c "service ssh restart";
    sudo docker logs --tail 100 ${NAME};
    echo "Docker created SUCCESSFULLY.";
    echo "Commands:"
    echo "--------------------------------- SSH ---------------------------------"
    echo "SSH COMMAND: ssh -p ${SSH_PORT} root@${MACHINE_NAME}";
    echo "------------------------------- PORT -------------------------------"
    echo "Your web service: http://${MACHINE_NAME}:${PORT}"
    
elif [ ${CMD} == "stop" ]; then
    sudo docker stop ${NAME};
    sudo docker rm ${NAME};
fi
